<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Villages;
use app\admin\model\User;
use app\admin\model\Member;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 活动
 */
class Activity extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = 2;
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'title' => [
                'label'     => '活动主题',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'

            ],
        ];
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();

            $joinModel = model('Joinactivity');
            foreach ($list as $item) {
                $item['countJoin'] = $joinModel->where(['activityId' => $item['id']])->count();
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        $areaMdl = new Area();
        $city = Helper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );

        return $this->view->fetch($this->addView, [
            'city' => $city,
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'pathtype' => 'add'
        ]);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        $area['cityName'] = getAreaName($info->cityId);
        $area['xianName'] = getAreaName($info->xianId);
        $area['townName'] = getAreaName($info->townId);
        if($info->villageId == '0'){
            $area['villageName'] = '0';
        }else{
            $Villages = Villages::get($info->villageId);
            $area['villageName'] = $Villages->name;
        }

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        $this->assign('area', $this->getArea($info));

        $info->startDate = date('Y-m-d', strtotime($info->startTime));
        $info->endDate = date('Y-m-d', strtotime($info->endTime));
        $info->startTime2 = substr($info->startTime, 11);
        $info->endTime2 = substr($info->endTime, 11);

        return $this->view->fetch($this->editView, [
            'info' => $info,
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'serarea' => $area,
            'pathtype' => 'edit'
        ]);

    }

    /**
     * Add/Edit Post
     */
    public function savePost(Request $request, $redirect = ''){
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();

            $data['startTime'] = strtotime($data['startDate'] . ' ' . $data['startTime']);
            $data['endTime'] = strtotime($data['endDate'] . ' ' . $data['endTime']);
            $data['deadline'] = strtotime($data['deadline']);

            if(isset($data['id']) && $data['id']){
                $data['updateDate'] = time();
                $data['updateOper'] = $this->admin->id;

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_update($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    return json(['code' => 1, 'msg' => '保存成功！', 'id' => $data['id'], 'url' => url('admin/' . strtolower($this->model) . '/index')]);
                } else {
                    return json(['code' => 0, 'msg' => $model->getError()]);
                }
            }

            // Insert data
            $data['id'] = Helper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;

            $result = $model->save($data);

            if($result !== false) {
                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                return json(['code' => 1, 'msg' => '添加成功！', 'id' => $data['id'], 'url' => url('admin/' . strtolower($this->model) . '/index')]);
            } else {
                return json(['code' => 0, 'msg' => $model->getError()]);
            }
        } else {
            return json(['code' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 详情
     */
    public function detail(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        $info->organization = $this->getOrganization($info->createOper);

        return $this->view->fetch('detail', [
            'info' => $info
        ]);
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                //$result = $model->where('id', $id)->update(['isDelete' => 1]);
                if($result !== false){
                    // 删除参加活动人员
                    $res = db('joinactivity')->where(['activityId' => $id])->delete();
                    if($res === false){
                        Db::rollback();
                        return $this->error('删除参加活动人员失败！', 'admin/' . strtolower($this->model) . '/index');
                    }

                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
        }

        return $where;
    }

    /**
     * 参加活动人员 列表
     * @return \think\response\Json
     */
    public function joinactivityList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Joinactivity');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'activityId' => $param['id']
        ];

        /*$join = [
            ['__USER__ u', 'a.userId = u.id'],
        ];
        $field = 'a.*, u.avatarUrl as avatar, u.nickName as name, u.memberId';
        $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->join($join)->count();

        foreach($list as $item){
            if($item['memberId']){
                $memberInfo = Member::where(['id' => $item['memberId']])->find();
                $item['avatar'] = $memberInfo['avatar'];
                $item['name'] = $memberInfo['name'];
            }
        }*/
        $field = 'a.*, a.userAvatar as avatar, a.userName as name';
        $list = $model->alias('a')->where($where)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

}